package com.chinamobile.websocket.websocket.filter;

import com.chinamobile.websocket.util.SpringContextUtil;
import com.chinamobile.websocket.websocket.common.WebsocketConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @className: WebsocketHandshakInteceptor
 * @description 拦截器
 * @author: fanzhijun
 * @date: 2024/1/18
 **/
@Component
public class WebsocketHandshakInteceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
            Map<String, Object> variables = (Map<String, Object>) serverRequest.getServletRequest().getAttribute(WebsocketConstant.PATH_VARIABLE_LEY);
            if (variables == null || variables.isEmpty()) {
                return false;
            }
            if (variables.get(WebsocketConstant.TYPE) == null) {
                return false;
            }
            String uniKey = String.valueOf(variables.get(WebsocketConstant.UNIKEY));
            String token = String.valueOf(variables.get(WebsocketConstant.TOKEN));
            if (StringUtils.isBlank(uniKey) || StringUtils.isBlank(token)) {
                return false;
            }
            attributes.putAll(variables);
            try {
                WebsocketConnectValid userTokenValid = SpringContextUtil.getApplicationContext().getBean(WebsocketConnectValid.class);
                return userTokenValid.valid(token);
            } catch (Exception e) {
                throw new RuntimeException("检查是否实现[WebsocketConnectValid]拦截器接口");
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception exception) {
    }

}